﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using mshtml;

namespace AAA.Web
{
    public class HtmlAction
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern int FindWindowEx(int hw,IntPtr hw2,string lpClassName, string lpWindowName);
        
        [DllImport("user32.dll")]
        public static extern long SendMessage(int hWnd,uint Msg);

        public const uint WM_LBUTTONUP = 0x0202;
        public const uint WM_LBUTTONDOWN = 0x0201;



        private static HtmlElement FindForm(HtmlDocument document, string strKey)
        {            
            try
            {
                foreach (HtmlElement form in document.Forms)
                {
                    if ((form.Name == strKey) ||
                       (form.Id == strKey) ||
                       (form.GetAttribute("action") == strKey))
                        return form;
                }
            }
            catch
            {
                
            }
            return null;
        }

        public static List<string> GetAllHref(HtmlDocument document)
        {
            return GetAllHref(document, null);
        }

        public static List<string> GetAllHref(HtmlDocument document, string strURL)
        {
            string strHref;
            List<string> lstHref = new List<string>();
            for (int i = 0; i < document.All.Count; i++)
            {
                if (document.All[i].TagName == "A")
                {
                    strHref = document.All[i].GetAttribute("href").ToString().Trim();

                    if (strURL != null)
                    {
                        if (strHref.IndexOf(strURL) > -1)
                            lstHref.Add(strHref);
                    }
                    else
                    {
                        lstHref.Add(strHref);
                    }
                }
            }
            return lstHref;
        }

        public static string HrefClick(HtmlDocument document, string strURL)
        {
            try
            {
                string strHref;
                List<string> lstHref = new List<string>();
                for (int i = 0; i < document.All.Count; i++)
                {
                    if (document.All[i].TagName == "A")
                    {
                        strHref = document.All[i].GetAttribute("href").ToString().Trim();
                        lstHref.Add(strHref);
                            
                    }

                      if (document.All[i].TagName == "A" && document.All[i].GetAttribute("href").ToString().Trim() == strURL)
                      {
                          document.All[i].InvokeMember("click");//引發”CLICK”事件
                          break;
                      }                    
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message + "," + ex.StackTrace;
            }
        }

        public static void FillTextAreaData(HtmlDocument document, string strFormName, string strName, string strValue)
        {
            //HtmlElement frmWord = document.Forms[strFormName];//找到from
            HtmlElement frmWord = FindForm(document, strFormName);
            if (frmWord == null)
                return;

            HtmlElementCollection cTextarea = frmWord.GetElementsByTagName("TEXTAREA");

            foreach (HtmlElement txtArea in cTextarea)
                if (txtArea.Name == strName)
                    txtArea.InnerText = strValue;

        }

        public static void ClickTextArea(HtmlDocument document, string strFormName, string strName)
        {
            //HtmlElement frmWord = document.Forms[strFormName];//找到from
            HtmlElement frmWord = FindForm(document, strFormName);
            if (frmWord == null)
                return;

            HtmlElementCollection cTextarea = frmWord.GetElementsByTagName("TEXTAREA");

            foreach (HtmlElement txtArea in cTextarea)
                if (txtArea.Name == strName)
                    txtArea.InvokeMember("click");

        }


        public static void FillTextAreaDataWithoutForm(HtmlDocument document, string strName, string strValue)
        {            
            HtmlElementCollection cTextarea = document.GetElementsByTagName("TEXTAREA");

            foreach (HtmlElement txtArea in cTextarea)
                if ((txtArea.Name == strName) || (txtArea.Id == strName))
                    txtArea.InnerText = strValue;

        }


        public static void FillTextFieldData(HtmlDocument document, string strFormName, string strName, string strValue)
        {
/*
            HtmlElement frmWord = null;
            foreach (HtmlElement form in document.GetElementsByTagName("FORM"))
            {
                if ((form.Id == strName) || (form.Name == strName) || (form.GetAttribute("id") == strName))
                {
                    frmWord = form;
                    break;
                }
            }

            if (frmWord == null)
                return;
*/
            //HtmlElement frmWord = document.Forms[strFormName];//找到from            

            HtmlElement frmWord = FindForm(document, strFormName);
            if (frmWord == null)
                return;

            HtmlElementCollection cTextarea = frmWord.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
                if ((txtArea.Name == strName) || ((txtArea.Id == strName)))
                    txtArea.InnerText = strValue;

        }

        public static void FillTextFieldDataWithoutForm(HtmlDocument document, string strName, string strValue)
        {            
            HtmlElementCollection cTextarea = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
                if ((txtArea.Name == strName) || (txtArea.Id == strName))
                    txtArea.InnerText = strValue;

        }


        public static void FillTextFieldData(HtmlDocument document, string strId, string strValue)
        {
            HtmlElementCollection cTextarea = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
                if (txtArea.Id == strId)
                    txtArea.InnerText = strValue;

        }


        public static void Submit(HtmlDocument document, string strFormName, string strName)
        {
            //HtmlElement frmWord = document.Forms[strFormName];//找到from
            HtmlElement frmWord = FindForm(document, strFormName);
            if (frmWord == null)
                return;

            HtmlElementCollection cTextarea = frmWord.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "SUBMIT")
                    continue;

                if ((txtArea.Name == strName) || (txtArea.Id == strName) || (txtArea.GetAttribute("value") == strName))
                    txtArea.InvokeMember("click");
            }
        }

        public static void ClickImage(HtmlDocument document, string strId, string strValue)
        {            
            HtmlElementCollection cTextarea = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "IMAGE")
                    continue;
                
                if (strId == null)
                {
                    if (txtArea.GetAttribute("value").ToString() == strValue)
                        txtArea.InvokeMember("click");
                }
                else
                {
                    if (txtArea.Id == strId)
                        txtArea.InvokeMember("click");
                }

            }
        }


        public static void ClickSubmitButton(HtmlDocument document, string strFormName, string strName)
        {
            HtmlElement frmWord = document.Forms[strFormName];//找到from
            HtmlElementCollection cTextarea = frmWord.GetElementsByTagName("BUTTON");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "SUBMIT")
                    continue;

                if ((txtArea.Name == strName) || (txtArea.Id == strName) || (txtArea.GetAttribute("title") == strName))
                    txtArea.InvokeMember("click");
            }
        }

        public static void ClickSubmitButtonById(HtmlDocument document, string strId)
        {
            HtmlElementCollection cTextarea = document.GetElementsByTagName("BUTTON");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "SUBMIT")
                    continue;
                if (txtArea.Id == strId)
                    txtArea.InvokeMember("click");
            }
        }

        public static void ClickSubmitButton(HtmlDocument document, string strId)
        {            
            HtmlElementCollection cTextarea = document.GetElementsByTagName("BUTTON");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.Id == strId)
                    txtArea.InvokeMember("click");
            }
        }



        public static void ClickButton(HtmlDocument document, string strName, string strValue)
        {            
            HtmlElementCollection cTextarea = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "BUTTON")
                    continue;

                if (strName == null)
                {
                    if (txtArea.GetAttribute("value").ToString() == strValue)
                        txtArea.InvokeMember("click");
                }
                else
                {
                    if (txtArea.Name == strName)
                        txtArea.InvokeMember("click");
                }
            }
        }

        public static void SetOptionValue(HtmlDocument document, string strId, string strValue)
        {
            HtmlElement element = document.GetElementById(strId);
            element.SetAttribute("value", strValue);

        }

        public static void ClickCheckButton(HtmlDocument document, string strName, string strValue)
        {
            HtmlElementCollection cTextarea = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "CHECKBOX")
                    continue;

                if (strName == null)
                {
                    if (txtArea.GetAttribute("value").ToString() == strValue)
                        txtArea.InvokeMember("click");
                }
                else
                {
                    if ((txtArea.Name == strName) || (txtArea.Id == strName))
                        txtArea.InvokeMember("click");
                }
            }
        }

        public static void ClickRadioButton(HtmlDocument document, string strName, string strValue)
        {
            HtmlElementCollection cTextarea = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement txtArea in cTextarea)
            {
                if (txtArea.GetAttribute("type").ToUpper() != "RADIO")
                    continue;
                if ((txtArea.Name == strName) && (txtArea.GetAttribute("value").ToString() == strValue))
                {
                        txtArea.InvokeMember("click");
                }
            }
        }


        public static void SimulateClickImage(WebBrowser webBrowser, HtmlDocument document, string strId, string strValue)
        {
            HtmlElement htmlElement = FindHtmlElement(document, "IMAGE", strId, strValue);
        }

        public static HtmlElement FindTableCell(HtmlElement rowElement, int iColIndex)
        {
            try
            {
                int iCurrentCol = 0;
                foreach (HtmlElement col in rowElement.Children)
                {
                    if (col.TagName.ToLower() == "td")
                    {
                        if (iColIndex == iCurrentCol)
                            return col;

                        iCurrentCol++;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return null;
        }

        public static HtmlElement FindTableRow(HtmlElement tableElement, int iRowIndex)
        {
            try
            {
                int iCurrentRow = 0;
                foreach (HtmlElement row in tableElement.Children)
                {
                    if (row.TagName.ToLower() == "tr")
                    {
                        if (iRowIndex == iCurrentRow)
                            return row;

                        iCurrentRow++;
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return null;
        }

        public static HtmlElement FindElement(HtmlElement element, string strName)
        {
            if (element.TagName.ToLower() == strName)
            {
                return element;
            }
            foreach (HtmlElement child in element.Children)
            {
                HtmlElement current = FindElement(child, strName);
                if (current != null)
                {
                    return current;
                }
            }
            return null;

        }

        private static HtmlElement FindHtmlElement(HtmlDocument document, string strType, string strName, string strValue)
        {
            HtmlElement htmlElement = null;
            HtmlElementCollection cInputElement = document.GetElementsByTagName("INPUT");

            foreach (HtmlElement inputElement in cInputElement)
            {
                if (inputElement.GetAttribute("type").ToUpper() != strType.ToUpper())
                    continue;

                if (strName == null)
                {
                    if (inputElement.GetAttribute("value").ToString() == strValue)
                    {
                        htmlElement = inputElement;
                        break;
                    }
                }
                else
                {
                    if (inputElement.Name == strName)
                    {
                        htmlElement = inputElement;
                        break;
                    }
                }
            }
            return htmlElement;
        }

        public static HtmlElement FindHtmlElementById(HtmlDocument document, string strType, string strId, string strValue)
        {
            HtmlElement htmlElement = null;
            HtmlElementCollection cInputElement = document.GetElementsByTagName("INPUT");            

            foreach (HtmlElement inputElement in cInputElement)
            {
                if (inputElement.GetAttribute("type").ToUpper() != strType.ToUpper())
                    continue;

                if (strId == null)
                {
                    if (inputElement.GetAttribute("value").ToString() == strValue)
                    {
                        htmlElement = inputElement;
                        break;
                    }
                }
                else
                {
                    if (inputElement.Id == strId)
                    {
                        htmlElement = inputElement;
                        break;
                    }
                }
            }
            return htmlElement;
        }


        public static HtmlElement FindHtmlFormById(HtmlDocument document, string strId)
        {
            HtmlElement htmlElement = null;
            HtmlElementCollection cInputElement = document.GetElementsByTagName("FORM");

            foreach (HtmlElement inputElement in cInputElement)
            {
                if (inputElement.Id == strId)
                {
                    htmlElement = inputElement;
                    break;
                }                
            }
            return htmlElement;
        }


        private static void SimulateClickElement(WebBrowser webBrowser, HtmlElement element)
        {
            try
            {
                int x = element.ClientRectangle.X;
                int y = element.ClientRectangle.X;
                IntPtr lParam = (IntPtr)((y << 16) | x); // The coordinates 
                IntPtr wParam = IntPtr.Zero; // Additional parameters for the click (e.g. Ctrl) 
                const uint downCode = 0x201; // Left click down code 
                const uint upCode = 0x202; // Left click up code 
                SendMessage(webBrowser.Handle, downCode, wParam, lParam);
                SendMessage(webBrowser.Handle, upCode, wParam, lParam);
            }
            catch { }        
        }

        public static void MaskAlertWindow(HtmlDocument document)
        {
            IHTMLWindow2 win = (IHTMLWindow2)document.Window.DomWindow;

            string strScript = @"function confirm() { return true; }" +
                               @"function alert() {}";
            win.execScript(strScript, "javascript");
        }

        public static void CloseAlertWindow()
        {
            string ClassName = "";
            string WindowName = "";
            int alertHandle = 0;
            int childHandle = 0;

            ClassName = "#32770";

            WindowName = "網頁訊息";

            alertHandle = FindWindow(ClassName, WindowName);

            if (alertHandle != 0)
            {
                childHandle = FindWindowEx(alertHandle, IntPtr.Zero, "Button", "確定");
                SendMessage(childHandle, WM_LBUTTONDOWN);
                SendMessage(childHandle, WM_LBUTTONUP);
            }
        }

/*
        private void callJsMethod(string jsfun,string jsParameter)//函数名字,函数参数
        {
            HtmlDocument doc = webBrowser1.Document;
            doc.InvokeScript(jsfun,new object[]...{jsParameter});
        }
*/
    }
}
